<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 基础布局 -->
      <page-tools show-before>
        <span slot="before">
          共{{ page.total }}条记录
        </span>
        <template slot="after">
          <el-button size="small" type="danger" @click="exportDate">简单表单excel导出</el-button>
          <el-button size="small" type="success" @click="exportDate(true)">复杂表单excel导出</el-button>
          <el-button size="small" type="info" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="primary" icon="plus" :disabled="!checkPermission('add-user')" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格 -->
      <el-card v-loading="loading">
        <el-table border="" :data="list">
          <!-- type=index表示索引下标加1 -->
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" prop="" align="center">
            <template v-slot="{row}">
              <img
                v-imagerror="require('@/./assets/common/bigUserHeader.png')"
                style="border-radius: 20%; width: 100px; height: 100px; padding: 10px"
                :src="row.staffPhoto"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>

          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 传入插槽 -->
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate('MM/dd/yyyy') }}
            </template>
          </el-table-column>

          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>

          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button size="small" type="text" @click="$router.push(`/employees/detail/${row.id}`)">查看 </el-button>
              <el-button size="small" type="text">转正 </el-button>
              <el-button size="small" type="text">调岗 </el-button>
              <el-button size="small" type="text">离职 </el-button>
              <el-button size="small" type="text" @click="editRole(row.id)">角色 </el-button>
              <el-button size="small" type="text" :disabled="!checkPermission('del-user')" @click="deleteEmployee(row.id)">删除 </el-button>
            </template>

          </el-table-column>
        </el-table>

        <el-row style="height: 80px" type="flex" justify="center" align="middle">
          <!-- 分页组件 layout分页组建的部件 -->
          <el-pagination
            :total="page.total"
            :current-page="page.page"
            :page-size="page.size"
            background
            layout="prev, pager, next"
            @current-change="changePage"
          />
        </el-row>

      </el-card>

    </div>
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
    >
      <el-row
        type="flex"
        justify="center"
      >
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

    <!-- 引入组件并放在页面中给子组件造的属性传值 -->
    <addEmployee :show-dialog.sync="showDialog" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees' // 引入枚举对象
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'

export default {
  components: {
    addEmployee, AssignRole
  },
  data() {
    return {
      EmployeeEnum, // 在data中定义数据
      page: { // 定义分页数据
        page: 1, // 默认第一页
        size: 10,
        total: 0
      },
      list: [],
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null // 记录当前用户点击的id
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      await new Promise(resolve => setTimeout(() => resolve(), 200))
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // formatter规则
    formatEmployment(row, column, cellValue, index) {
      const obj = this.EmployeeEnum.hireType.find(item => (item.id + '') === (cellValue + '')) // 找满足条件的对象
      return obj ? obj.value : '未知' // 需要返回值
    },
    // 删除功能
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportDate(isComplex) { // 导出excel
    // 定义对应关系- 把英文的key转为中文的key对应关系
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载 script-loader
      import('@/vendor/Export2Excel').then(async excel => {
      // 此时表示该模块已经动态引入
        // excel.export_json_to_excel({
        //   header: ['姓名', '学历', '财产'], // 表头 必填
        //   data: [['花无缺', '大专', '100'], ['邀月', '博士', '9999']], // 具体数据 必填
        //   filename: 'excel-list', // 非必填
        //   autoWidth: true, // 非必填
        //   bookType: 'xlsx' // 非必填
        // })
        // 得到data数据导出数据-导出所有数据 获取 page-size 页码 每页条数 total 1000 size 10 100  size 1000 获取1次
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // 此时rows[{}, {}, {}] => [[],[],[]]
        const multiHeader = isComplex ? [['姓名', '主要信息', '', '', '', '', '部门']] : []
        const merges = isComplex ? ['A1:A2', 'B1:F1', 'G1:G2'] : []
        const data = this.formatJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data, // es6
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader,
          merges
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => { // item 是rows里面的每条数据
        return Object.values(headers).map(value => { // 字段名数组里的每条数据
          if (value === 'formOfEmployment') { // 当字段为聘用形式的时候 匹配其对应的文本
            const obj = this.EmployeeEnum.hireType.find(ele => (ele.id + '') === (item[value] + ''))
            return obj ? obj.value : '未知'
          } else if (value === 'timeOfEntry' || value === 'correctionTime') { // 当字段是日期时格式化日期
            return formatDate(item[value])
          }
          return item[value]
        })
      })
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }

}
</script>

<style>

</style>
